{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8d10861f-a550-4443-bc63-4ce2ae13b841",
   "metadata": {},
   "source": [
    "# Infino\n",
    "\n",
    "This example shows how one can track the following while calling OpenAI models via `LangChain` and [Infino](https://github.com/infinohq/infino):\n",
    "\n",
    "* prompt input,\n",
    "* response from `ChatGPT` or any other `LangChain` model,\n",
    "* latency,\n",
    "* errors,\n",
    "* number of tokens consumed"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64d14c88-b71c-4524-ab1b-4250a7dbb62b",
   "metadata": {},
   "source": [
    "## Initializing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed46c894-caa6-49b2-85d1-f275374fa308",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install necessary dependencies.\n",
    "!pip install infinopy\n",
    "!pip install matplotlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a5a0976-9953-41d8-880c-eb3f2992e936",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Remove the (1) import sys and sys.path.append(..) and (2) uncomment `!pip install langchain` after merging the PR for Infino/LangChain integration.\n",
    "import sys\n",
    "\n",
    "sys.path.append(\"../../../../../langchain\")\n",
    "\n",
    "\n",
    "import datetime as dt\n",
    "import json\n",
    "from langchain.llms import OpenAI\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.dates as md\n",
    "import os\n",
    "import time\n",
    "import sys\n",
    "\n",
    "from infinopy import InfinoClient\n",
    "from langchain.callbacks import InfinoCallbackHandler"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f90210d-c805-4a0c-81e4-d5298942afc4",
   "metadata": {},
   "source": [
    "## Start Infino server, initialize the Infino client"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "748b9858-5145-4351-976a-ca2d54e836a6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "497a621125800abdd19f57ce7e033349b3cf83ca8cea6a74e8e28433a42ecadd\n"
     ]
    }
   ],
   "source": [
    "# Start server using the Infino docker image.\n",
    "!docker run --rm --detach --name infino-example -p 3000:3000 infinohq/infino:latest\n",
    "\n",
    "# Create Infino client.\n",
    "client = InfinoClient()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6b81cda-b841-43ee-8c5e-b1576555765f",
   "metadata": {},
   "source": [
    "## Read the questions dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "b659fd0c-0d8c-470e-8b6c-867a117f2a27",
   "metadata": {},
   "outputs": [],
   "source": [
    "# These are a subset of questions from Stanford's QA dataset -\n",
    "# https://rajpurkar.github.io/SQuAD-explorer/\n",
    "data = \"\"\"In what country is Normandy located?\n",
    "When were the Normans in Normandy?\n",
    "From which countries did the Norse originate?\n",
    "Who was the Norse leader?\n",
    "What century did the Normans first gain their separate identity?\n",
    "Who gave their name to Normandy in the 1000's and 1100's\n",
    "What is France a region of?\n",
    "Who did King Charles III swear fealty to?\n",
    "When did the Frankish identity emerge?\n",
    "Who was the duke in the battle of Hastings?\n",
    "Who ruled the duchy of Normandy\n",
    "What religion were the Normans\n",
    "What type of major impact did the Norman dynasty have on modern Europe?\n",
    "Who was famed for their Christian spirit?\n",
    "Who assimilted the Roman language?\n",
    "Who ruled the country of Normandy?\n",
    "What principality did William the conquerer found?\n",
    "What is the original meaning of the word Norman?\n",
    "When was the Latin version of the word Norman first recorded?\n",
    "What name comes from the English words Normans/Normanz?\"\"\"\n",
    "\n",
    "questions = data.split(\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dce1b820-3f1a-4b94-b848-4c6032cadc18",
   "metadata": {},
   "source": [
    "## LangChain OpenAI Q&A; Publish metrics and logs to Infino"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "d5cebf35-2d10-48b8-ab11-c4a574c595d2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In what country is Normandy located?\n",
      "generations=[[Generation(text='\\n\\nNormandy is located in France.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 16, 'completion_tokens': 9, 'prompt_tokens': 7}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('8de21639-acec-4bd1-a12d-8124de1e20da'))\n",
      "When were the Normans in Normandy?\n",
      "generations=[[Generation(text='\\n\\nThe Normans first settled in Normandy in the late 9th century.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 24, 'completion_tokens': 16, 'prompt_tokens': 8}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('cf81fc86-250b-4e6e-9d92-2df3bebb019a'))\n",
      "From which countries did the Norse originate?\n",
      "generations=[[Generation(text='\\n\\nThe Norse originated from Scandinavia, which includes modern-day Norway, Sweden, and Denmark.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 29, 'completion_tokens': 21, 'prompt_tokens': 8}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('50f42f5e-b4a4-411a-a049-f92cb573a74f'))\n",
      "Who was the Norse leader?\n",
      "generations=[[Generation(text='\\n\\nThe most famous Norse leader was the legendary Viking king Ragnar Lodbrok. He is believed to have lived in the 9th century and is renowned for his exploits in England and France.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 45, 'completion_tokens': 39, 'prompt_tokens': 6}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('e32f31cb-ddc9-4863-8e6e-cb7a281a0ada'))\n",
      "What century did the Normans first gain their separate identity?\n",
      "generations=[[Generation(text='\\n\\nThe Normans first gained their separate identity in the 11th century.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 28, 'completion_tokens': 16, 'prompt_tokens': 12}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('da9d8f73-b3b3-4bc5-8495-da8b11462a51'))\n",
      "Who gave their name to Normandy in the 1000's and 1100's\n",
      "generations=[[Generation(text='\\n\\nThe Normans, a people from northern France, gave their name to Normandy in the 1000s and 1100s. The Normans were descended from Viking settlers who had come to the region in the late 800s.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 58, 'completion_tokens': 45, 'prompt_tokens': 13}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('bb5829bf-b6a6-4429-adfa-414ac5be46e5'))\n",
      "What is France a region of?\n",
      "generations=[[Generation(text='\\n\\nFrance is a region of Europe.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 16, 'completion_tokens': 9, 'prompt_tokens': 7}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('6943880b-b4e4-4c74-9ca1-8c03c10f7e9c'))\n",
      "Who did King Charles III swear fealty to?\n",
      "generations=[[Generation(text='\\n\\nKing Charles III swore fealty to Pope Innocent III.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 23, 'completion_tokens': 13, 'prompt_tokens': 10}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('c91fd663-09e6-4d00-b746-4c7fd96f9ceb'))\n",
      "When did the Frankish identity emerge?\n",
      "generations=[[Generation(text='\\n\\nThe Frankish identity began to emerge in the late 5th century, when the Franks began to expand their power and influence in the region. The Franks were a Germanic tribe that had migrated to the area from the east and had established a kingdom in what is now modern-day France. The Franks were eventually able to establish a powerful kingdom that lasted until the 10th century.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 86, 'completion_tokens': 78, 'prompt_tokens': 8}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('23f86775-e592-4cb8-baa3-46ebe74305b2'))\n",
      "Who was the duke in the battle of Hastings?\n",
      "generations=[[Generation(text='\\n\\nThe Duke of Normandy, William the Conqueror, was the leader of the Norman forces at the Battle of Hastings in 1066.', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 39, 'completion_tokens': 28, 'prompt_tokens': 11}, 'model_name': 'text-davinci-003'} run=RunInfo(run_id=UUID('ad5b7984-8758-4d95-a5eb-ee56e0218f6b'))\n"
     ]
    }
   ],
   "source": [
    "# Set your key here.\n",
    "# os.environ[\"OPENAI_API_KEY\"] = \"YOUR_API_KEY\"\n",
    "\n",
    "# Create callback handler. This logs latency, errors, token usage, prompts as well as prompt responses to Infino.\n",
    "handler = InfinoCallbackHandler(\n",
    "    model_id=\"test_openai\", model_version=\"0.1\", verbose=False\n",
    ")\n",
    "\n",
    "# Create LLM.\n",
    "llm = OpenAI(temperature=0.1)\n",
    "\n",
    "# Number of questions to ask the OpenAI model. We limit to a short number here to save $$ while running this demo.\n",
    "num_questions = 10\n",
    "\n",
    "questions = questions[0:num_questions]\n",
    "for question in questions:\n",
    "    print(question)\n",
    "\n",
    "    # We send the question to OpenAI API, with Infino callback.\n",
    "    llm_result = llm.generate([question], callbacks=[handler])\n",
    "    print(llm_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b68ec697-c922-4fd9-aad1-f49c6ac24e8a",
   "metadata": {},
   "source": [
    "## Create Metric Charts\n",
    "\n",
    "We now use matplotlib to create graphs of latency, errors and tokens consumed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f078c612-89e0-4a1d-b1a8-bf36b664a10e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Helper function to create a graph using matplotlib.\n",
    "def plot(data, title):\n",
    "    data = json.loads(data)\n",
    "\n",
    "    # Extract x and y values from the data\n",
    "    timestamps = [item[\"time\"] for item in data]\n",
    "    dates = [dt.datetime.fromtimestamp(ts) for ts in timestamps]\n",
    "    y = [item[\"value\"] for item in data]\n",
    "\n",
    "    plt.rcParams[\"figure.figsize\"] = [6, 4]\n",
    "    plt.subplots_adjust(bottom=0.2)\n",
    "    plt.xticks(rotation=25)\n",
    "    ax = plt.gca()\n",
    "    xfmt = md.DateFormatter(\"%Y-%m-%d %H:%M:%S\")\n",
    "    ax.xaxis.set_major_formatter(xfmt)\n",
    "\n",
    "    # Create the plot\n",
    "    plt.plot(dates, y)\n",
    "\n",
    "    # Set labels and title\n",
    "    plt.xlabel(\"Time\")\n",
    "    plt.ylabel(\"Value\")\n",
    "    plt.title(title)\n",
    "\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "response = client.search_ts(\"__name__\", \"latency\", 0, int(time.time()))\n",
    "plot(response.text, \"Latency\")\n",
    "\n",
    "response = client.search_ts(\"__name__\", \"error\", 0, int(time.time()))\n",
    "plot(response.text, \"Errors\")\n",
    "\n",
    "response = client.search_ts(\"__name__\", \"prompt_tokens\", 0, int(time.time()))\n",
    "plot(response.text, \"Prompt Tokens\")\n",
    "\n",
    "response = client.search_ts(\"__name__\", \"completion_tokens\", 0, int(time.time()))\n",
    "plot(response.text, \"Completion Tokens\")\n",
    "\n",
    "response = client.search_ts(\"__name__\", \"total_tokens\", 0, int(time.time()))\n",
    "plot(response.text, \"Total Tokens\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3d61822-1781-4bc6-97a2-2abc5c2b2e75",
   "metadata": {},
   "source": [
    "## Full text query on prompt or prompt outputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "a0f051f0-e2bc-44e7-8dfb-bfd5bbd0fc9f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Results for normandy : [{\"time\":1686821979,\"fields\":{\"prompt\":\"In what country is Normandy located?\"},\"text\":\"In what country is Normandy located?\"},{\"time\":1686821982,\"fields\":{\"prompt_response\":\"\\n\\nNormandy is located in France.\"},\"text\":\"\\n\\nNormandy is located in France.\"},{\"time\":1686821984,\"fields\":{\"prompt_response\":\"\\n\\nThe Normans first settled in Normandy in the late 9th century.\"},\"text\":\"\\n\\nThe Normans first settled in Normandy in the late 9th century.\"},{\"time\":1686821993,\"fields\":{\"prompt\":\"Who gave their name to Normandy in the 1000's and 1100's\"},\"text\":\"Who gave their name to Normandy in the 1000's and 1100's\"},{\"time\":1686821997,\"fields\":{\"prompt_response\":\"\\n\\nThe Normans, a people from northern France, gave their name to Normandy in the 1000s and 1100s. The Normans were descended from Viking settlers who had come to the region in the late 800s.\"},\"text\":\"\\n\\nThe Normans, a people from northern France, gave their name to Normandy in the 1000s and 1100s. The Normans were descended from Viking settlers who had come to the region in the late 800s.\"}]\n",
      "===\n",
      "Results for king charles III : [{\"time\":1686821998,\"fields\":{\"prompt\":\"Who did King Charles III swear fealty to?\"},\"text\":\"Who did King Charles III swear fealty to?\"},{\"time\":1686822000,\"fields\":{\"prompt_response\":\"\\n\\nKing Charles III swore fealty to Pope Innocent III.\"},\"text\":\"\\n\\nKing Charles III swore fealty to Pope Innocent III.\"}]\n"
     ]
    }
   ],
   "source": [
    "# Search for a particular prompt text.\n",
    "query = \"normandy\"\n",
    "response = client.search_log(query, 0, int(time.time()))\n",
    "print(\"Results for\", query, \":\", response.text)\n",
    "\n",
    "print(\"===\")\n",
    "\n",
    "query = \"king charles III\"\n",
    "response = client.search_log(\"king charles III\", 0, int(time.time()))\n",
    "print(\"Results for\", query, \":\", response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b171074-c775-48e0-a4b3-f550e2c8eccb",
   "metadata": {},
   "source": [
    "## Stop infino server"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "147663cb-b88f-4cfb-9726-7231dbec7cc1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "infino-example\n"
     ]
    }
   ],
   "source": [
    "!docker rm -f infino-example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "86f36c49-53a3-460d-b74b-995cda7726b3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
